package com.example.nacosdemo.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

/**
 * 诊断控制器 - 提供基本的健康检查和配置信息
 * 即使Nacos不可用，这个控制器也能正常工作
 */
@RestController
public class DiagnosticController {

    private static final Logger logger = LoggerFactory.getLogger(DiagnosticController.class);
    
    // 从本地配置获取默认值，确保即使Nacos不可用也能正常工作
    @Value("${demo.config.message:默认诊断消息}")
    private String message;
    
    @Value("${demo.config.timeout:30}")
    private int timeout;
    
    @Value("${demo.config.enabled:true}")
    private boolean enabled;
    
    /**
     * 健康检查端点
     */
    @GetMapping("/health-check")
    public Map<String, Object> healthCheck() {
        Map<String, Object> response = new HashMap<>();
        response.put("status", "UP");
        response.put("service", "nacos-demo-service");
        response.put("timestamp", System.currentTimeMillis());
        logger.info("健康检查请求处理成功");
        return response;
    }
    
    /**
     * 配置检查端点 - 显示当前配置值
     */
    @GetMapping("/config-check")
    public Map<String, Object> configCheck() {
        Map<String, Object> response = new HashMap<>();
        response.put("message", message);
        response.put("timeout", timeout);
        response.put("enabled", enabled);
        response.put("source", "本地配置或Nacos（如果可用）");
        logger.info("配置检查请求处理成功，当前message: {}", message);
        return response;
    }
    
    /**
     * 系统环境检查
     */
    @GetMapping("/env-check")
    public Map<String, String> envCheck() {
        Map<String, String> response = new HashMap<>();
        
        // 获取Nacos相关环境变量
        response.put("NACOS_SERVER_ADDR", System.getenv("NACOS_SERVER_ADDR"));
        response.put("NACOS_USERNAME", System.getenv("NACOS_USERNAME"));
        // 不输出密码，只检查是否存在
        String password = System.getenv("NACOS_PASSWORD");
        response.put("NACOS_PASSWORD_SET", password != null ? "是" : "否");
        
        // 获取系统属性
        response.put("java.version", System.getProperty("java.version"));
        response.put("os.name", System.getProperty("os.name"));
        
        logger.info("环境检查请求处理成功");
        return response;
    }
    
    /**
     * 简单的演示端点，不依赖Nacos
     */
    @GetMapping("/demo")
    public String demo() {
        logger.info("演示端点被访问");
        return "应用运行正常！即使Nacos连接失败，应用仍可以提供基本服务。";
    }
}